package com.wang.work;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @BelongsProject: RabbitMqLearn
 * @BelongsPackage: com.wang
 * @Author: wang fei
 * @CreateTime: 2023-02-03  16:49
 * @Description: TODO RabbitMq work队列模式（能者多劳）消费者,消费者先声明⼀次只接收⼀条消息： channel.basicQos(1),消费者关闭⾃动ack
 * @Version: 1.0
 */
public class MyConsumer1 {
    public static final String QUEUE_NAME ="my_work_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        //获取链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.206.130");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("wang");
        connectionFactory.setPassword("123456");
        connectionFactory.setVirtualHost("/test1");
        //获得链接对像
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();
        //表示⼀次只接收⼀条消息
        channel.basicQos(1);

        //创建Consumer对象,指明具体的消息处理程序
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                //处理信息,并且进行业务逻辑处理,打印信息
                System.out.println(message);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //⼿动ack 传的是消息的Tag标记，⽤来表示当前处理的这条消息
                channel.basicAck(envelope.getDeliveryTag(),true);
            }
        };
        //设置消费者监听queue("my_queue"),把⾃动ack改为⼿动ack
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }
}

